package cn.gson.crm.control.staff;

import java.net.URLEncoder;
import java.sql.Date;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.sun.media.jfxmedia.track.Track.Encoding;

import cn.gson.crm.control.base.BaseServlet;
import cn.gson.crm.model.dao.DeptDao;
import cn.gson.crm.model.dao.PositionDao;
import cn.gson.crm.model.dao.StaffDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.entity.Dept;
import cn.gson.crm.model.entity.Position;
import cn.gson.crm.model.entity.Staff;
import cn.gson.crm.model.entity.StaffVo;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.entity.StudentVo;

/**
 * Servlet implementation class StaffServlet
 */
@WebServlet("/staff")
public class StaffServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	StaffDao  staff=new StaffDao();
	DeptDao dept =new DeptDao();
	PositionDao pos=new PositionDao();
	StudentDao studao=new StudentDao();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StaffServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
			String method=request.getParameter("method");
			if("login".equalsIgnoreCase(method)){
				login(request,response);
			}
			if("select".equalsIgnoreCase(method)){
				select(request,response);
			}
			if("delete".equalsIgnoreCase(method)){
				delete(request,response);
			}
			if("insert".equalsIgnoreCase(method)){
				insert(request,response);
			}
			if("update".equalsIgnoreCase(method)){
				update(request,response);
			}
			if("selectby".equalsIgnoreCase(method)){
				selectby(request,response);
			}
			if("updateStaff".equalsIgnoreCase(method)){
				updateStaff(request,response);
			}
			if("forward".equalsIgnoreCase(method)){
				forward(request,response);
			}
			if("staff".equalsIgnoreCase(method)){
				staff(request,response);
			}
			if("selectstaffname".equalsIgnoreCase(method)){
				selectstaffname(request,response);
			}
	}



	private void selectstaffname(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name=request.getParameter("name");
		Staff s=staff.getStaffByName(name);
		boolean b=false;
			if(s!=null){
				b=true;
			}else{
				b=false;
		}
			response.setContentType("application/json;charset=utf-8");
	    	String jsonStr = JSONArray.toJSONString(b);
	        //输出结果
	        response.getWriter().append(jsonStr);		
	}

	private void staff(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id =request.getSession().getAttribute("schid").toString();
		String names=request.getSession().getAttribute("names").toString();
		List<StudentVo> liststu=studao.getStudenByallot(id);
		List<StudentVo> coostu=studao.getStudenBycoopera(id);
		request.setAttribute("names", names);
		request.setAttribute("allotstu", liststu);
		request.setAttribute("coostu", coostu);
		int size1=0;
		int size2=0;
		if(liststu!=null&&!liststu.isEmpty()){
		size1=liststu.size();
		}
		if(coostu!=null&&!coostu.isEmpty()){
		 size2=coostu.size();
		}
		request.setAttribute("size1", size1);
		request.setAttribute("size2", size2);
		java.util.Date now=new java.util.Date();
		SimpleDateFormat  format=new SimpleDateFormat("yyyy-MM");
		String date=format.format(now);
		int countbenyue=staff.getStaffCount(id, date);
		int countzong=staff.getStaffCount(id, "");
		request.setAttribute("countbenyue", countbenyue);
		request.setAttribute("countzong", countzong);
		int countcoobenyue=staff.getStaffCoo(id, date);
		int countcoozong=staff.getStaffCoo(id, "");
		request.setAttribute("countcoobenyue", countcoobenyue);
		request.setAttribute("countcoozong", countcoozong);
		forward("main2.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void post(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		get(request, response);
	}

	/**
	 * 登录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		pwd = addPass(pwd);
		Staff map=staff.getStaffByNameAndPwd(name, pwd);
		if(map!=null){
			int id = map.getStaffId();
			request.getSession().setAttribute("schid", id);
			String names = map.getStaffName();
			request.getSession().setAttribute("names", names);
			request.getSession().setAttribute("staff", map);
			redirect("staff?method=staff");
		}else{
			request.setAttribute("errors", "用户名或密码错误");
			forward("../../login2.jsp");;
		}
	}
	/**
	 * 登录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void forward(HttpServletRequest request, HttpServletResponse response) throws Exception{
		redirect("staff?method=staff");
	}
	
	/**
	 * 查询
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	@SuppressWarnings("null")
	private void select(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String page=request.getParameter("page");
		if(page==null||page.isEmpty()){
			page="1";
		}
		int totalPage=staff.getTotal();
		int pages=Integer.parseInt(page);
		List<Map<String,Object>> list=staff.getStaffLimit(pages);
		 List<Staff>  lists=staff.getStaff();
		int allcount=lists.size();
		List<Position> poslist=pos.getJobInformation();
		List<Dept> deptlist=dept.getList();
		request.setAttribute("page", pages);
		request.setAttribute("allcount", allcount);
		request.setAttribute("totalPage", totalPage);
		request.setAttribute("list", list);
		request.setAttribute("deptlist", deptlist);
		request.setAttribute("poslist", poslist);
		forward("staff/staff.jsp");
	}
	
	/**
	 * 删除
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String[] id=request.getParameterValues("id");
		for (int i = 0; i < id.length; i++) {
			staff.deleteStaff(id[i]);
		}
			selectby(request,response);
	}
	
	/**
	 *新增员工 
	 * @param request
	 * @param responses
	 * @throws SQLException 
	 */
	private void insert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name=request.getParameter("name");
		System.out.println(name);
		List<Staff>  map=staff.getStaff();
		int a = map.size();
		int i = 0;
		for (Staff ss : map) {
			if(ss.getStaffName().equals(name)){
				String errors=URLEncoder.encode("该员工已存在","utf-8");
				redirect("staff?method=selectby&errors="+errors);
				break;
			}else{
				a= a-1;
				if(a==0){
					String sex=request.getParameter("sex");
					String address=request.getParameter("address");
					String phone=request.getParameter("phone");
					String email=request.getParameter("email");
					String position=request.getParameter("position");
					String dept=request.getParameter("dept");
					String pwd=request.getParameter("pwd");
					pwd = addPass(pwd);
					Staff s=new Staff();
					s.setStaffName(name);
					s.setStaffAddress(address);
					s.setStaffPhone(phone);
					s.setStaffSex(Integer.parseInt(sex));
					s.setStaffPassword(pwd);
					s.setStaffPositionId(Integer.parseInt(position));
					s.setStaffDeptId(Integer.parseInt(dept));
					s.setStaffEmail(email);
					staff.insertStaff(s);
					redirect("staff?method=selectby");
					break;
				}
					
				}
		}
		
	}

	/**
	 * 修改员工
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id=request.getParameter("id");
		StaffVo
		s=staff.getStaffByIds(id);
		request.setAttribute("s", s);
		List<Position> poslist=pos.getJobInformation();
		List<Dept> d=new DeptDao().getList();
		request.setAttribute("deptlist", d);
		request.setAttribute("poslist", poslist);
		forward("staff/StaffUpdate.jsp");
	}

	/**
	 * 修改员工
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	private void updateStaff(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String id=request.getParameter("id");
		String name=request.getParameter("name");
		String sex=request.getParameter("sex");
		String address=request.getParameter("address");
		String phone=request.getParameter("phone");
		String email=request.getParameter("email");
		String position=request.getParameter("position");
		String dept=request.getParameter("dept");
		Staff s=new Staff();
		s.setStaffId(Integer.parseInt(id));
		s.setStaffName(name);
		s.setStaffSex(Integer.parseInt(sex));
		s.setStaffPhone(phone);
		s.setStaffEmail(email);
		s.setStaffAddress(address);
		s.setStaffPositionId(Integer.parseInt(position));
		s.setStaffDeptId(Integer.parseInt(dept));
		staff.updateStaffById(s);
		selectby(request,response);
	}
	/**
	 * 条件查询员工
	 * @param request
	 * @param response
	 * @throws SQLException 
	 */
	private void selectby(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String errors=request.getParameter("errors");
		if(errors!=null&&!errors.isEmpty()){
			request.setAttribute("errors", errors);
		}
		String name=request.getParameter("names");
		String sex=request.getParameter("sexs");
		String address=request.getParameter("addresss");
		String phone=request.getParameter("phones");
		String aa="";
		String date=request.getParameter("dates");
		if(date!=null&&!date.isEmpty()){
		aa=java.sql.Date.valueOf(date).toString();
		}
		String position=request.getParameter("positions");
		String dept=request.getParameter("depts");
		String status=request.getParameter("status");
		String page=request.getParameter("page");
	
		if(page==null||page.isEmpty()){
			page="1";
		}
		int pages=Integer.parseInt(page);
		int totalPage=staff.getTotal(status, aa, name, phone, address, sex, dept, position);
		List<Map<String,Object>> list=	staff.getStaffBy(pages,status, aa, name, phone, address, sex, dept, position);
		List<Map<String,Object>> lists=staff.getStaff(status, aa, name, phone, address, sex, dept, position);
		int allcount=lists.size();
		List<Position> poslist=pos.getJobInformation();
		List<Dept> d=new DeptDao().getList();
		request.setAttribute("queryString", noPageQueryString(request));
		request.setAttribute("page", pages);
		request.setAttribute("allcount", allcount);
		request.setAttribute("totalPage", totalPage);
		request.setAttribute("list", list);
		request.setAttribute("deptlist", d);
		request.setAttribute("poslist", poslist);
		forward("staff/staff.jsp");
	}
	private String noPageQueryString(HttpServletRequest request) {
		Map<String, String[]> params = request.getParameterMap();

		String paramsStr = "";
		int i = 0;
		for (String key : params.keySet()) {
			if ("page".equals(key)) {
				continue;
			}
			String[] valus = params.get(key);
			String query = "";
			for (int j = 0; j < valus.length; j++) {
				query += key + "=" + valus[j];
				if (j < valus.length - 1) {
					query += "&";
				}
			}
			paramsStr += query;
			if (i < params.keySet().size() - 1) {
				paramsStr += "&";
			}
			i++;
		}
		return paramsStr.isEmpty() ? "" : "&" + paramsStr;
	}
}
